/*
 * logrw_util.c
 *
 *  Created on: Nov 16, 2011
 *      Author: rui
 */

#include <stdlib.h>
#include <stdio.h>
#include "../include/logrw.h"
#include "../include/block.h"
#include <sthread.h>
#include <assert.h>
#include "logrw_util.h"
#include "logrw.h"
#include <logrw.h>


void reg_print(reg_t* r){
	printf("reg:=%d ",r->reg);
	printf("index:%d ",r->y);
	printf("array:%d ",r->x);
}

void reg_init(reg_t *r,int index, int array){
	assert( r != NULL);
	r->reg=index;
	r->y=index;
	r->x=array;
	mutex_init( (&r->mutex));
}

void reg_free(reg_t *r){
	assert( r != NULL);
	mutex_destroy(&(r->mutex));
}

void* safeMalloc( size_t size){
	void* pointer=NULL;
	assert( (pointer=malloc(size)) != NULL);
	return pointer;
}

void mutex_init(mutex_t *m){
	m->mutex = sthread_rwlock_init();
	m->mutex_count = sthread_mutex_init();
	m->count=0;
}

void mutex_destroy(mutex_t *m){
	sthread_mutex_free(m->mutex_count);
	sthread_rwlock_destroy(m->mutex);
}

int mutex_unlock(mutex_t *m) {
	int result = 0;
	sthread_mutex_lock(m->mutex_count);
	sthread_rwlock_unlock(m->mutex);
	m->count--;
	sthread_mutex_unlock(m->mutex_count);
	return result;
}
// devolve 0 se houve sucesso e -1 caso contrario
int mutex_wrlock(mutex_t *m) {
	int result = 0;
	sthread_mutex_lock(m->mutex_count);
	m->count++;
	sthread_mutex_unlock(m->mutex_count);
	sthread_rwlock_wrlock(m->mutex);
	return result;
}
// devolve 0 se houve sucesso e -1 caso contrario
int mutex_rdlock(mutex_t *m) {
	int result = 0;
	sthread_mutex_lock(m->mutex_count);
	m->count++;
	sthread_mutex_unlock(m->mutex_count);
	sthread_rwlock_rdlock(m->mutex);
	return result;
}
// devolve 0 se conseguiu o trinco, -1 se o trinco estava bloqueado
int mutex_trylock(mutex_t *m) {
	int result;
	sthread_mutex_lock(m->mutex_count);
	if (m->count == 0) {
		m->count++;
		sthread_rwlock_wrlock(m->mutex);
		result = 0;
	} else {
		result = -1;
	}
	sthread_mutex_unlock(m->mutex_count);
	return result;
}

